package com.guo.xiao.bing.controller;

import com.github.pagehelper.PageInfo;
import com.guo.xiao.bing.entity.News;
import com.guo.xiao.bing.entity.ProjectType;
import com.guo.xiao.bing.entity.User;
import com.guo.xiao.bing.service.NewsService;
import com.guo.xiao.bing.service.ProjectTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("news")
public class NewsController {

    @Autowired
    NewsService newsService;

    @RequestMapping(value = "{page}", method = RequestMethod.GET)
    public String list(@PathVariable Integer page, Model model) {
        PageInfo<News> pageInfo = newsService.find(page);
        model.addAttribute("page", pageInfo);
        return "news/list";
    }

    @RequestMapping(value = "add", method = RequestMethod.GET)
    public String add(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        if ("admin".equals(user.getUsername())) {
            return "news/add";
        } else {
            return "redirect:/news/1";
        }
    }

    @RequestMapping(value = "add", method = RequestMethod.POST)
    public String add(HttpSession session, @ModelAttribute News news) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        if ("admin".equals(user.getUsername())) {
            newsService.save(news);
        }
        return "redirect:/news/1";
    }


    @RequestMapping(value = "del/{id}", method = RequestMethod.GET)
    public String del(@PathVariable Integer id, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        if ("admin".equals(user.getUsername())) {
            newsService.delete(id);
        }

        return "redirect:/news/1";
    }

    @RequestMapping(value = "show/{id}", method = RequestMethod.GET)
    public String show(@PathVariable Integer id, Model model) {
        News news = newsService.findById(id);

        model.addAttribute("news", news);
        return "news/show";
    }

}
